<?php

namespace App\Models;

use App\Models\Scopes\ActiveScope;
use App\Traits\Presenter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Overtrue\Pinyin\Pinyin;

class Actor extends Model
{
    use Presenter;

    protected $fillable = [
        'title',
        'picture',
        'show',
        'abbr',
    ];

    protected $casts = [
        'show' => 'bool',
    ];

    protected $attributes = [
        'show' => true,
    ];

    /**
     * 自动观察 演员名称
     */
    protected static function booted(): void
    {
        static::addGlobalScope(new ActiveScope);

        static::saving(function (Actor $actor) {
            if ($actor->isDirty('title')) {
                $actor->abbr = Pinyin::abbr($actor->title, 'none')->join('');
            }
        });
    }

    /**
     * 视频
     */
    public function videos(): BelongsToMany
    {
        return $this->belongsToMany(Video::class);
    }

    /**
     * 收藏
     */
    public function favorites(): MorphMany
    {
        return $this->morphMany(Favorite::class, 'favorite');
    }
}
